package com.yamed.bus.service.kakfa;

import com.alibaba.fastjson.JSONObject;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.common.TopicPartition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Duration;
import java.util.*;

/**
 * @Author: wchen
 * @Description:
 * @Date: Created in 2019-08-19 15:42
 * Copyright 本内容仅限于杭州阿拉丁信息科技股份有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */
public class ConsumerApi {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private KafkaConsumer kafkaConsumer;

    ConsumerApi(){
        Properties props = new Properties();
        props.put("bootstrap.servers", "192.168.111.34:9092");
        props.put("group.id", "group-my-topic");
        props.put("enable.auto.commit", "true");
        props.put("auto.commit.interval.ms", "10000");

        props.put("max.poll.records", "10");
        props.put("max.poll.interval.ms", "30000");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        kafkaConsumer = new KafkaConsumer<>(props);
    }

    public KafkaConsumer getKafkaConsumer() {
        return kafkaConsumer;
    }

    /**
     * 订阅主题
     */
    public void subscribeTopic() throws Exception{
        kafkaConsumer.subscribe(Arrays.asList("my-topic", "bar"));
        int i =0 ;
        Set<TopicPartition> partitions = null;
        while (true) {
            i ++;
            ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofSeconds(5));
//            if(records.partitions().size() > 0){
//                partitions = records.partitions();
//                kafkaConsumer.pause(partitions);
//            }
            logger.info("subscribeTopic.records.partitions:" + JSONObject.toJSONString(partitions));
            Set<TopicPartition> topicPartitions = kafkaConsumer.paused();
            logger.info("subscribeTopic.topicPartitions:" + JSONObject.toJSONString(topicPartitions));

            logger.info(String.format("subscribeTopic : %s", records.count()));
            for (ConsumerRecord<String, String> record : records) {
                logger.info(String.format("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value()));
            }
            Thread.sleep(1000 * 5);
            System.out.println("**********************" + i + "***********************");
//            if(i > 5){
//                kafkaConsumer.resume(partitions);
//            }
        }
    }


    /**
     * 所有收到的消息至为已提交
     * @throws Exception
     */
    public void consumerByHandle() throws Exception{
        Properties props = new Properties();
        props.put("bootstrap.servers", "47.105.166.188:9092");
        props.put("group.id", "test");
        props.put("enable.auto.commit", "false");
        props.put("auto.commit.interval.ms", "10000");
        props.put("session.timeout.ms", "30000");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
        consumer.subscribe(Arrays.asList("my-topic", "bar"));
        final int minBatchSize = 200;
        List<ConsumerRecord<String, String>> buffer = new ArrayList<>();
        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(5));
            logger.info(String.format("subscribeTopic : %s", JSONObject.toJSONString(records, true)));
            for (ConsumerRecord<String, String> record : records) {
                buffer.add(record);
                logger.info(String.format("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value()));
            }
            if (buffer.size() >= minBatchSize) {
//                insertIntoDb(buffer);
                consumer.commitSync();
                Thread.sleep(1000 * 10);
                buffer.clear();
            }
            Thread.sleep(1000 * 5);
        }
    }

    public void consumerHandle2(){
        Properties props = new Properties();
        props.put("bootstrap.servers", "47.105.166.188:9092");
        props.put("group.id", "test");
        props.put("enable.auto.commit", "false");
        props.put("auto.commit.interval.ms", "10000");
        props.put("session.timeout.ms", "30000");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
        consumer.subscribe(Arrays.asList("my-topic", "bar"));
        final int minBatchSize = 200;
        List<ConsumerRecord<String, String>> buffer = new ArrayList<>();
        try {
            while(true) {
                ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(5));
                for (TopicPartition partition : records.partitions()) {
                    List<ConsumerRecord<String, String>> partitionRecords = records.records(partition);
                    for (ConsumerRecord<String, String> record : partitionRecords) {
                        System.out.println(record.offset() + ": " + record.value());
                    }
                    long lastOffset = partitionRecords.get(partitionRecords.size() - 1).offset();
                    consumer.commitSync(Collections.singletonMap(partition, new OffsetAndMetadata(lastOffset + 1)));
                }
            }
        } finally {
            consumer.close();
        }
    }


    public static void main(String[] args) throws Exception{
        ConsumerApi consumerApi = new ConsumerApi();
        consumerApi.subscribeTopic();
//        consumerApi.consumerByHandle();
    }

}
